package com.ship.dispatch.service.boats.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ship.dispatch.bean.BoatsAisMessage;
import com.ship.dispatch.bean.boats.info.QueryAisInfo;
import com.ship.dispatch.mapper.boats.BoatsAisMessageMapper;
import com.ship.dispatch.service.boats.BoatsAisMessageService;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * <b>BoatsAisMessageServiceImpl</b>
 *
 * @description: BoatsAisMessageServiceImpl <br>
 * @date: 2024/5/30 15:49 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class BoatsAisMessageServiceImpl extends ServiceImpl<BoatsAisMessageMapper, BoatsAisMessage> implements BoatsAisMessageService {

    @Override
    public List<QueryAisInfo> queryAisByShipName(String shipName, String imo, String startDate, String endDate) throws ParseException {
        List<QueryAisInfo> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区为UTC
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date parse = sdf.parse(startDate);
        Date parse1 = sdf.parse(endDate);
        long queryStartTime = parse.getTime()/1000;
        long queryEndTime = parse1.getTime()/1000;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate startTime= LocalDate.parse(startDate, formatter);
        LocalDate endTime = LocalDate.parse(endDate, formatter);
        LocalDate currentDate = startTime;
        while (!currentDate.isAfter(endTime)) {
            ZonedDateTime zonedDateTime = currentDate.atStartOfDay(ZoneId.systemDefault());
            Date date = Date.from(zonedDateTime.toInstant());
            String format = DateUtil.format(date, DatePattern.PURE_DATE_FORMATTER);
            String tableName = "boats_ais_message" + format;
            String status = baseMapper.queryTableName(tableName);
            if ("t".equals(status)){
                List<QueryAisInfo> boatsPerformanceList = baseMapper.queryAisByShipName(shipName,imo,startDate,endDate,tableName);
                if (CollectionUtil.isNotEmpty(boatsPerformanceList)){
                    list.addAll(boatsPerformanceList);
                }
            }
            currentDate = currentDate.plusDays(1);
        }
        return list;
    }
}
